package com.ruoyi.task.service.impl;

import com.ruoyi.common.core.domain.dto.LevelCommentDto;
import com.ruoyi.common.core.domain.dto.StringIntegerMapDto;
import com.ruoyi.common.core.domain.dto.TaskCommentReviewDto;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.service.IFileService;
import com.ruoyi.task.domain.Task;
import com.ruoyi.task.domain.TaskComment;
import com.ruoyi.task.mapper.TaskCommentMapper;
import com.ruoyi.task.service.ITaskCommentService;
import com.ruoyi.task.service.ITaskService;
import com.ruoyi.wechat.domain.WechatUser;
import com.ruoyi.wechat.service.IWechatUserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 任务评论Service业务层处理
 *
 * @author KevenPotter
 * @date 2024-04-29 13:48:05
 */
@Service
@AllArgsConstructor
public class TaskCommentServiceImpl implements ITaskCommentService {

    private final ITaskService taskService;
    private final IWechatUserService wechatUserService;
    private final IFileService fileService;
    private final TaskCommentMapper taskCommentMapper;

    /**
     * 查询任务评论
     *
     * @param id 任务评论主键
     * @return 任务评论
     */
    @Override
    public TaskComment getById(Long id) {
        return taskCommentMapper.getById(id);
    }

    /**
     * 根据[任务编号]获取任务评论
     *
     * @param taskId 任务编号
     * @return 返回根据[任务编号]获取任务评论
     * @author KevenPotter
     * @date 2024-04-30 14:05:21
     */
    @Override
    public List<TaskComment> getByTaskId(Long taskId) {
        return taskCommentMapper.getByTaskId(taskId);
    }

    /**
     * 根据[任务编号]获取任务评论数量
     *
     * @param taskId 任务编号
     * @return 返回根据[任务编号]获取任务评论数量
     * @author KevenPotter
     * @date 2024-05-02 20:39:57
     */
    @Override
    public int getCommentCountsByTaskId(Long taskId) {
        return taskCommentMapper.getCommentCountsByTaskId(taskId);
    }

    /**
     * 根据[任务编号]获取一级任务评论
     *
     * @param taskId 任务编号
     * @return 返回根据[任务编号]获取一级任务评论
     * @author KevenPotter
     * @date 2024-04-30 14:33:01
     */
    @Override
    public List<TaskComment> getLevel1List(Long taskId) {
        return taskCommentMapper.getLevel1List(taskId);
    }

    /**
     * 根据[任务编号]获取二级任务评论
     *
     * @param taskId 任务编号
     * @return 返回根据[任务编号]获取二级任务评论
     * @author KevenPotter
     * @date 2024-04-30 14:33:19
     */
    @Override
    public List<TaskComment> getLevel2List(Long taskId) {
        return taskCommentMapper.getLevel2List(taskId);
    }

    /**
     * 查询任务评论列表
     *
     * @param taskComment 任务评论
     * @return 任务评论
     */
    @Override
    public List<TaskComment> getList(TaskComment taskComment) {
        return taskCommentMapper.getList(taskComment);
    }

    /**
     * 新增任务评论
     *
     * @param taskComment 任务评论
     * @return 结果
     */
    @Override
    public int insertTaskComment(TaskComment taskComment) {
        taskComment.setCreateTime(DateUtils.getNowDate());
        if (taskComment.getToUserId() == 0) taskComment.setLevel("1").setToCommentId(0L);
        else taskComment.setLevel("2").setToCommentId(taskComment.getToCommentId());
        return taskCommentMapper.insertTaskComment(taskComment);
    }

    /**
     * 修改任务评论
     *
     * @param taskComment 任务评论
     * @return 结果
     */
    @Override
    public int updateTaskComment(TaskComment taskComment) {
        if (taskComment.getToUserId() == 0) taskComment.setLevel("1").setToCommentId(0L);
        else taskComment.setLevel("2").setToCommentId(taskComment.getToCommentId());
        return taskCommentMapper.updateTaskComment(taskComment);
    }

    /**
     * 批量删除任务评论
     *
     * @param ids 需要删除的任务评论主键
     * @return 结果
     */
    @Override
    public int deleteTaskCommentByIds(Long[] ids) {
        return taskCommentMapper.deleteTaskCommentByIds(ids);
    }

    /**
     * 删除任务评论信息
     *
     * @param id 任务评论主键
     * @return 结果
     */
    @Override
    public int deleteTaskCommentById(Long id) {
        return taskCommentMapper.deleteTaskCommentById(id);
    }

    /**
     * 审核任务评论
     *
     * @param taskCommentReviewDto 任务评论审核数据传输
     * @return 返回是否审核成功
     * @author KevenPotter
     * @date 2024-04-29 15:17:20
     */
    @Override
    public int review(TaskCommentReviewDto taskCommentReviewDto) {
        Integer reviewStatus = taskCommentReviewDto.getReviewStatus();
        if (Objects.equals(reviewStatus, 98)) {
            return taskCommentMapper.reviewReject(taskCommentReviewDto);
        } else if (Objects.equals(reviewStatus, 99)) {
            return taskCommentMapper.reviewPass(taskCommentReviewDto);
        }
        return 0;
    }

    /**
     * 获取带级别的评论列表
     *
     * @param taskId 任务编号
     * @return 返回带级别的评论列表
     * @author KevenPotter
     * @date 2024-04-30 14:08:12
     */
    @Override
    public List<LevelCommentDto> getLevelComment(Long taskId) {
        // 获取一级、二级列表
        List<TaskComment> level1List = this.getLevel1List(taskId);
        List<TaskComment> level2List = this.getLevel2List(taskId);
        List<LevelCommentDto> levelCommentList = new ArrayList<>();
        // 一级列表的评论全部打入初始化的评论列表
        level1List.forEach(level1 -> {
            WechatUser wechatUser = wechatUserService.getById(level1.getFromUserId());
            LevelCommentDto comment = new LevelCommentDto().setLevel(1);
            comment.setCommentId(level1.getId()).setComment(level1.getComment()).setCreateTime(level1.getCreateTime());
            comment.setFromUserId(wechatUser.getId()).setFromUserName(wechatUser.getNickName()).setFromUserAvatar(
                    wechatUser.getAvatar().contains("https") ? wechatUser.getAvatar() : fileService.buildSingleFileUrlFullPath(wechatUser.getAvatar())
            ).setFromUserMobile(wechatUser.getMobile());
            String commentImage = level1.getCommentImage();
            if (StringUtils.isNotEmpty(commentImage)) {
                comment.setCommentImage(String.join(SPLIT, fileService.buildMultipleFileUrlsFullPath(commentImage)));
                comment.setCommentImageList(fileService.buildMultipleFileUrlsFullPath(commentImage));
            }
            levelCommentList.add(comment);
        });
        // 二级列表进行值匹配
        level2List.forEach(level2 -> {
            WechatUser fromUser = wechatUserService.getById(level2.getFromUserId()), toUser = wechatUserService.getById(level2.getToUserId());
            Long commentId = level2.getToCommentId();
            Long ancestorCommentId = getAncestorCommentId(commentId);
            List<LevelCommentDto> subLevel1List = levelCommentList.stream().filter(level1Item -> level1Item.getCommentId().equals(ancestorCommentId)).collect(Collectors.toList());
            LevelCommentDto comment = new LevelCommentDto().setLevel(2);
            comment.setCommentId(level2.getId()).setComment(level2.getComment()).setCreateTime(level2.getCreateTime());
            comment.setFromUserId(fromUser.getId()).setFromUserName(fromUser.getNickName()).setFromUserAvatar(
                    fromUser.getAvatar().contains("https") ? fromUser.getAvatar() : fileService.buildSingleFileUrlFullPath(fromUser.getAvatar())
            ).setFromUserMobile(fromUser.getMobile());
            comment.setToUserId(toUser.getId()).setToUserName(toUser.getNickName()).setToUserAvatar(
                    toUser.getAvatar().contains("https") ? toUser.getAvatar() : fileService.buildSingleFileUrlFullPath(toUser.getAvatar())
            ).setToUserMobile(toUser.getMobile());
            String commentImage = level2.getCommentImage();
            if (StringUtils.isNotEmpty(commentImage)) {
                comment.setCommentImage(String.join(SPLIT, fileService.buildMultipleFileUrlsFullPath(commentImage)));
                comment.setCommentImageList(fileService.buildMultipleFileUrlsFullPath(commentImage));
            }
            subLevel1List.get(0).getCommentReply().add(comment);
        });
        return levelCommentList;
    }

    /**
     * 查询评论总数
     *
     * @return 返回评论总数
     * @author KevenPotter
     * @date 2024-05-01 20:08:23
     */
    @Override
    public int getTaskCommentCounts() {
        return taskCommentMapper.getTaskCommentCounts();
    }

    /**
     * 查询近期评论数据
     *
     * @return 返回期评论数据
     * @author KevenPotter
     * @date 2024-05-01 22:11:25
     */
    @Override
    public List<StringIntegerMapDto> getRecentlyCommentCounts() {
        return taskCommentMapper.getRecentlyCommentCounts();
    }

    /**
     * 获取祖先编号(也就是获取评论链root)
     *
     * @param commentId 评论编号
     * @return 返回祖先编号
     * @author KevenPotter
     * @date 2024-04-30 16:05:12
     */
    private Long getAncestorCommentId(Long commentId) {
        TaskComment taskComment = taskCommentMapper.getById(commentId);
        if (taskComment.getToUserId() == 0) return taskComment.getId();
        else return getAncestorCommentId(taskComment.getToCommentId());
    }

    /**
     * 过滤出埠参数参数
     *
     * @param taskComment 任务评论对象
     * @param loginUser   当前登录对象
     * @return 返回过滤后的[任务评论对象]
     * @author KevenPotter
     * @date 2024-04-29 14:00:00
     */
    @Override
    public TaskComment filterInbound(TaskComment taskComment, LoginUser loginUser) {
        if (StringUtils.isNotEmpty(taskComment.getCommentImage())) taskComment.setCommentImage(FileUtils.buildFilesUrl(taskComment.getCommentImage().split(SPLIT)));
        if (taskComment.getTaskId() != null) {
            Task task = taskService.getById(taskComment.getTaskId());
            taskComment.setTaskTitle(task.getTitle()).setItem(task.getItem());
        }
        return taskComment;
    }

    /**
     * 过滤出埠参数参数
     *
     * @param taskComment 任务评论对象
     * @param loginUser   当前登录对象
     * @return 返回过滤后的[任务评论对象]
     * @author KevenPotter
     * @date 2024-04-29 14:00:06
     */
    @Override
    public TaskComment filterOutbound(TaskComment taskComment, LoginUser loginUser) {
        if (StringUtils.isNotEmpty(taskComment.getCommentImage())) {
            String commentImage = taskComment.getCommentImage();
            taskComment.setCommentImage(String.join(SPLIT, fileService.buildMultipleFileUrlsFullPath(commentImage)));
            taskComment.setCommentImageList(fileService.buildMultipleFileUrlsFullPath(commentImage));
        }
        if (taskComment.getTaskId() != null) taskComment.setTaskInfo(taskService.getById(taskComment.getTaskId()).getTaskInfo());
        if (taskComment.getFromUserId() != null && taskComment.getFromUserId() == 0) taskComment.setFromUserName("当前任务");
        else if (taskComment.getFromUserId() != null) taskComment.setFromUserName(wechatUserService.getById(taskComment.getFromUserId()).getNickName());
        if (taskComment.getToUserId() != null && taskComment.getToUserId() == 0) taskComment.setToUserName("当前任务");
        else if (taskComment.getToUserId() != null) taskComment.setToUserName(wechatUserService.getById(taskComment.getToUserId()).getNickName());
        return taskComment;
    }
}
